<template>
    <div class="manage-profile-page">
        <el-card>
            <h2 style="text-align: center; margin-bottom: 24px">
                主页信息管理
            </h2>
            <div
                style="
                    display: flex;
                    gap: 16px;
                    align-items: center;
                    margin-bottom: 16px;
                "
            >
                <!-- 搜索名称 -->
                <el-input
                    v-model="searchName"
                    placeholder="搜索主页名称"
                    clearable
                    style="width: 200px"
                />
            </div>
            <el-table :data="pagedData" style="width: 100%">
                <el-table-column prop="name" label="名称" width="120" />
                <el-table-column prop="img" label="图片" width="120">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.img"
                            :src="scope.row.img"
                            style="width: 4rem; height: 6rem"
                            fit="contain"
                            :preview-src-list="[scope.row.img]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="video" label="视频" width="280">
                    <template #default="scope">
                        <video
                            v-if="scope.row.video"
                            :src="scope.row.video"
                            style="width: 16rem"
                            controls
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="Layers" label="图层" width="80" />
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button
                            size="small"
                            type="primary"
                            @click="openEdit(scope.row)"
                            round
                            >编辑</el-button
                        >
                        <el-popconfirm
                            title="确定删除该主页数据吗？"
                            @confirm="handleDelete(scope.row)"
                            confirm-button-text="删除"
                            cancel-button-text="取消"
                        >
                            <template #reference>
                                <el-button size="small" type="danger" round
                                    >删除</el-button
                                >
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; margin: 24px 0">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :page-size="pageSize"
                    :total="filteredData.length"
                    v-model:current-page="currentPage"
                />
            </div>
        </el-card>
        <!-- 编辑对话框 -->
        <el-dialog
            v-model="showEditDialog"
            title="编辑主页数据"
            width="900px"
            center
        >
            <el-form>
                <el-form-item label="名称">
                    <el-input v-model="editRow.name" />
                </el-form-item>
                <el-form-item label="图片链接">
                    <el-input v-model="editRow.img" />
                </el-form-item>
                <el-form-item label="视频链接">
                    <el-input v-model="editRow.video" />
                </el-form-item>
                <el-form-item label="（越大图片越往右）">
                    <el-input-number v-model="editRow.left" :min="0" />
                </el-form-item>
                <el-form-item label="（越大图片越往下）">
                    <el-input-number v-model="editRow.top" :min="0" />
                </el-form-item>
                <el-form-item label="（图片宽度）">
                    <el-input-number v-model="editRow.width" :min="0" />
                </el-form-item>
                <el-form-item label="（图片高度）">
                    <el-input-number v-model="editRow.height" :min="0" />
                </el-form-item>
                <el-form-item label="（越大名字越往上）">
                    <el-input-number v-model="editRow.nameTop" :min="0" />
                </el-form-item>
                <el-form-item label="（越小名字越往左）">
                    <el-input-number v-model="editRow.nameRight" />
                </el-form-item>
                <el-form-item label="（名字背景的宽度）">
                    <el-input-number
                        v-model="editRow.nameBgImgWidht"
                        :min="0"
                    />
                </el-form-item>
                <el-form-item
                    label="（名字背景的高度，推荐数值：两字2，三字5，四字7，5字8，六字9）"
                >
                    <el-input-number
                        v-model="editRow.nameBgImgHeight"
                        :min="0"
                    />
                </el-form-item>
                <el-form-item label="Layers（数字越大，图层越高）">
                    <el-input-number v-model="editRow.Layers" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showEditDialog = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="handleEdit"
                    :loading="editLoading"
                    >保存</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getAllHomeData, updateHomeData, deleteHomeData } from "./api";

const homeDataList = ref([]);
const searchName = ref("");
const currentPage = ref(1);
const pageSize = 5;

// 过滤和分页
const filteredData = computed(() => {
    return homeDataList.value.filter((item) => {
        return searchName.value
            ? (item.name || "").includes(searchName.value)
            : true;
    });
});
const pagedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return filteredData.value.slice(start, start + pageSize);
});

// 编辑相关
const showEditDialog = ref(false);
const editRow = ref({
    _id: "",
    name: "",
    img: "",
    video: "",
    left: 0,
    top: 0,
    width: 12,
    height: 23,
    nameTop: 10,
    nameRight: -4,
    nameBgImgWidht: 2,
    nameBgImgHeight: 7,
    Layers: 0,
});
const editLoading = ref(false);

const operatorId = sessionStorage.getItem("user_id");

// 获取所有主页数据
function fetchHomeData() {
    getAllHomeData().then((res) => {
        homeDataList.value = res;
        currentPage.value = 1;
    });
}

// 打开编辑
function openEdit(row) {
    editRow.value = Object.assign(
        {
            _id: "",
            name: "",
            img: "",
            video: "",
            left: 0,
            top: 0,
            width: 12,
            height: 23,
            nameTop: 10,
            nameRight: -4,
            nameBgImgWidht: 2,
            nameBgImgHeight: 7,
            Layers: 0,
        },
        row
    );
    showEditDialog.value = true;
}

// 保存编辑
function handleEdit() {
    editLoading.value = true;
    updateHomeData(editRow.value._id, {
        operatorId,
        name: editRow.value.name,
        img: editRow.value.img,
        video: editRow.value.video,
        left: editRow.value.left,
        top: editRow.value.top,
        width: editRow.value.width,
        height: editRow.value.height,
        nameTop: editRow.value.nameTop,
        nameRight: editRow.value.nameRight,
        nameBgImgWidht: editRow.value.nameBgImgWidht,
        nameBgImgHeight: editRow.value.nameBgImgHeight,
        Layers: editRow.value.Layers,
    })
        .then((res) => {
            ElMessage.success(res.message);
            showEditDialog.value = false;
            fetchHomeData();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "更新失败");
        })
        .finally(() => {
            editLoading.value = false;
        });
}

// 删除数据
function handleDelete(row) {
    deleteHomeData(row._id, { operatorId })
        .then((res) => {
            ElMessage.success(res.message);
            fetchHomeData();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "删除失败");
        });
}

onMounted(fetchHomeData);
</script>